/*
 * This file is part of the eccOS Library.
 * Copyright (C) 2007.
 *
 * Version: MPL 1.1/GPL 2.0/LGPL 2.1
 *
 * The contents of this file are subject to the Mozilla Public License Version
 * 1.1 (the "License"); you may not use this file except in compliance with
 * the License. You may obtain a copy of the License at
 * http://www.mozilla.org/MPL/
 *
 * Software distributed under the License is distributed on an "AS IS" basis,
 * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
 * for the specific language governing rights and limitations under the
 * License.
 *
 * Alternatively, the contents of this file may be used under the terms of
 * either the GNU General Public License Version 2 or later (the "GPL"), or
 * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
 * in which case the provisions of the GPL or the LGPL are applicable instead
 * of those above. If you wish to allow use of your version of this file only
 * under the terms of either the GPL or the LGPL, and not to allow others to
 * use your version of this file under the terms of the MPL, indicate your
 * decision by deleting the provisions above and replace them with the notice
 * and other provisions required by the GPL or the LGPL. If you do not delete
 * the provisions above, a recipient may use your version of this file under
 * the terms of any one of the MPL, the GPL or the LGPL.
 */
package org.openeccos.internal;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;

import nextapp.echo2.app.Alignment;
import nextapp.echo2.app.Border;
import nextapp.echo2.app.Button;
import nextapp.echo2.app.Color;
import nextapp.echo2.app.Column;
import nextapp.echo2.app.Component;
import nextapp.echo2.app.Extent;
import nextapp.echo2.app.Font;
import nextapp.echo2.app.Grid;
import nextapp.echo2.app.Insets;
import nextapp.echo2.app.Row;
import nextapp.echo2.app.event.ActionEvent;
import nextapp.echo2.app.event.ActionListener;
import nextapp.echo2.app.event.ChangeEvent;
import nextapp.echo2.app.event.ChangeListener;

import org.openeccos.dao.EccosRepository;
import org.openeccos.dao.EccosService;
import org.openeccos.dao.HeaderValue;
import org.openeccos.gui.PDMessageBox;
import org.openeccos.model.IEccleEntry;
import org.openeccos.model.MBase;
import org.openeccos.model.MDefaultEccleEntry;
import org.openeccos.properties.EccleEditorProperties;
import org.openeccos.util.EccosDefaultLookAndFeel;
import org.openeccos.util.PDUtil;

import com.sas.framework.expojo.ModelExposer;

import echopointng.Strut;
import echopointng.able.Expandable;
import echopointng.model.DefaultExpansionModel;
import echopointng.model.ExpansionGroup;
import echopointng.model.ExpansionModel;

/**
 *
 *
 * @author cgspinner@web.de
 */
public abstract class EccleEditorPane<T> extends Column implements Expandable {

	protected Button btnCancel;
	protected Button btnDelete;
	protected Button btnEdit;
	protected Button btnSave;
	protected Button btnTitle;
	protected Row commandRow;
	protected boolean deleteable;
	protected boolean editable;
	protected HeaderValue headerValues;
	protected int index; // Sections need to know where they are, so that the pagination works.
	protected boolean bodyInitialized;
	protected ExpansionModel expansionModel = new DefaultExpansionModel();
	private T model; //MBaseWithTitle model class
	protected Grid titleBarGrid;
	protected ActionListener titleChangeListener;
	protected ActionListener dataChangeListener;
	protected boolean isEditing;

	public EccleEditorPane(HeaderValue headerValues, boolean editable) {
		this(headerValues, editable, true);
	}

	public EccleEditorPane(HeaderValue headerValues, boolean editable, boolean deleteable) {
		this.headerValues = headerValues;
		this.editable = editable;
		this.deleteable = deleteable;
		initInternal();
	}

	public Button addCommand(String text, String image, String toolTipText) {
		Button btn = new Button();
		btn.setBorder(new Border(0, null, Border.STYLE_NONE));
		btn.setInsets(new Insets(3, 0, 0, 0));
		btn.setHeight(new Extent(16));
		btn.setRolloverEnabled(false);
		btn.setForeground(Color.DARKGRAY);
		if (image != null) {
			btn.setIcon(PDUtil.getImage(image));
		} else {
			btn.setInsets(new Insets(0, 3, 0, 0));
		}
		if (toolTipText != null) {
			btn.setToolTipText(toolTipText);
		}
		if (text != null) {
			btn.setText(text);
			btn.setFont(new Font(Font.VERDANA, Font.PLAIN, new Extent(9)));
			btn.setIconTextMargin(new Extent(2));
		}
		commandRow.add(btn);
		return btn;
	}

	protected void addCommands() {
		//override if applicable
	}

	protected abstract void applyToModel();

	protected void btnDeleteClicked() {
		if (getModel() instanceof MBase && !((MBase)getModel()).isDeleteable()) {
			PDMessageBox.msgBox("Error", "The selected entry can't be deleted!", 300, 200);
			return;
		}
		PDMessageBox.confirmMsgBox(new ActionListener() {
			public void actionPerformed(ActionEvent evt) {
				btnDeleteClickedBis();
			}
		});
	}

	protected void btnDeleteClickedBis() {
		EccosService service =(EccosService)ModelExposer.get().getService(EccosService.NAME);
		service.delete(getModel());
		fireDataChanged();
	}
	
	public void fireDataChanged() {
		if (dataChangeListener != null) {
			dataChangeListener.actionPerformed(new ActionEvent(getModel(), ""));
		}
	}

	public void btnEditClicked() {
		if (!isExpanded()) {
			setExpanded(true);
		}
		setEditing(true);
		onEdit();
	}

	protected void setEditing(boolean editing) {
		btnEdit.setVisible(!editing);
		btnCancel.setVisible(editing);
		btnSave.setVisible(editing);
		isEditing = editing;
	}

	protected abstract void doLazyLoad();

	public ExpansionGroup getExpansionGroup() {
		throw new UnsupportedOperationException();
	}

	public ExpansionModel getExpansionModel() {
		return expansionModel;
	}

	public int getIndex() {
		return index;
	}

	public T getModel() {
		if (model == null) {
			//lazy loading - use only when the section gets expanded!
			EccosRepository repo = (EccosRepository)ModelExposer.get().getRepository(EccosRepository.NAME);
			Type modelClass = ((ParameterizedType) getClass().getGenericSuperclass()).getActualTypeArguments()[0];
			model = (T)repo.loadById((Class)modelClass, headerValues.identifier);
		}
		return model;
	}

	protected void initEditingCommands() {
		// extend is needed
	}

	protected void initGUI() {
		setBorder(new Border(0, Color.DARKGRAY, Border.STYLE_SOLID));

		titleBarGrid = new Grid(2);
		titleBarGrid.setWidth(new Extent(100, Extent.PERCENT));
		titleBarGrid.setHeight(new Extent(19));
		titleBarGrid.setBackground(EccosDefaultLookAndFeel.EXP_SECTION_BACKROUND);
		add(titleBarGrid);

		btnTitle = new Button(PDUtil.getImage("img/arrowleft.gif"));
		btnTitle.setInsets(new Insets(0));
		btnTitle.setHeight(new Extent(16));
		btnTitle.setForeground(Color.BLACK);
		btnTitle.setBorder(new Border(0, null, Border.STYLE_NONE));
		btnTitle.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				setExpanded(!isExpanded());
			}
		});
		titleBarGrid.add(btnTitle);

		commandRow = new Row();
		commandRow.setAlignment(new Alignment(Alignment.RIGHT, Alignment.DEFAULT));
		titleBarGrid.add(commandRow);

		initEditingCommands();

		if (editable) {
			commandRow.add(new Strut(11, 0));

			btnEdit = addCommand(null, "img/edit.gif", EccleEditorProperties.editEntry());
			btnEdit.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					btnEditClicked();
				}
			});

			btnCancel = addCommand(null, "img/undo.gif", EccleEditorProperties.cancel());
			btnCancel.setVisible(false);
			btnCancel.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					setEditing(false);
					onCancel();
				}
			});

			btnSave = addCommand(null, "img/save.gif", EccleEditorProperties.save());
			btnSave.setVisible(false);
			btnSave.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					setEditing(false);
					onSave();
				}
			});
		}
	}

	protected void initInternal() {
		initGUI();
		updateHeader();
		addCommands();

		if (deleteable) {
			commandRow.add(new Strut(6, 0));
			btnDelete = addCommand(null, "img/deletee.gif", EccleEditorProperties.deleteEntry());
			btnDelete.addActionListener(new ActionListener() {
				public void actionPerformed(ActionEvent e) {
					btnDeleteClicked();
				}
			});
		}

		getExpansionModel().addChangeListener(new ChangeListener() {
			public void stateChanged(ChangeEvent arg0) {
				if (!bodyInitialized) {
					doLazyLoad();
					setEnabled2();
					bodyInitialized = true;
				}
				readFromModel();
			}
		});
	}

	public boolean isExpanded() {
		return expansionModel.isExpanded();
	}

	protected void onCancel() {
		readFromModel();
		updateHeader();
		setEnabled2();
	}

	protected void onEdit() {
		setEnabled2();
	}

	protected void onSave() {
		String preSaveResult = preSave();
		if (preSaveResult != null) {
			return;
		}
		applyToModel();
		EccosService service =(EccosService)ModelExposer.get().getService(EccosService.NAME);
		((IEccleEntry)getModel()).setNewEntryDate(null);
		service.persist(getModel());
		postSave();
		fireHeaderValuesChanged();
		setEnabled2();
	}

	protected String preSave() {
		return null; //override if needed
	}

	protected void postSave() {
		//override if needed
	}

	protected abstract void readFromModel();

	protected abstract void setEnabled2();

	public void setExpanded(boolean expanded) {
		if (isExpanded() == expanded) {
			return;
		}
		setInternalExpanded(expanded);
	}

	public void setExpansionGroup(ExpansionGroup expansionGroup) {
		throw new UnsupportedOperationException();
	}

	public void setExpansionModel(ExpansionModel expansionModel) {
		this.expansionModel = expansionModel;
	}

	public void setIndex(int index) {
		this.index = index;
	}

	private void setInternalExpanded(boolean expanded) {
		expansionModel.setExpanded(expanded);
		if (expanded) {
			btnTitle.setIcon(PDUtil.getImage("img/arrowdown.gif"));
		} else {
			btnTitle.setIcon(PDUtil.getImage("img/arrowleft.gif"));
		}

		for (int i = 1; i < getComponentCount(); i++) {
			Component component = getComponent(i);
			component.setVisible(expanded);
		}
	}

	public void setTitleChangeListener(ActionListener titleChangeListener) {
		this.titleChangeListener = titleChangeListener;
	}

	public void setDataChangedListener(ActionListener dataChangeListener) {
		this.dataChangeListener = dataChangeListener;
	}

	protected void updateHeader() {
		btnTitle.setText(headerValues.title);
	}

	protected void fireHeaderValuesChanged() {
		if (getModel() instanceof MDefaultEccleEntry) {
			((MDefaultEccleEntry)getModel()).updateCachedTitle();
		}
		headerValues.title = ((IEccleEntry)getModel()).getCachedTitle();
		updateHeader();
		if (titleChangeListener != null) {
			titleChangeListener.actionPerformed(new ActionEvent(headerValues, ""));
		}
	}

	@Override
	public void setBackground(Color c) {
		titleBarGrid.setBackground(c);
	}
}